﻿using System;
using System.Collections.Generic;
using System.Linq; 
using NTTDATA.BEENChina.ResultCertification.Config;
using NTTDATA.BEENChina.ResultCertification.Util;
using NTTDATA.BEENChina.ResultCertification.Split;
using NTTDATA.BEENChina.ResultCertification.model;

namespace NTTDATA.BEENChina.ResultCertification.Checker.Address
{   
    [Serializable]
    [VerfityAttribute(Id = "VerfityA0003", Name = "Mansion名检证", CategoryType = EnumCategoryType.住所, Model = true)]
    public class VerfityA0003 : VerfityOneResult
    {       
 
        public override bool CheckResult(List<List<string>> result, string entryCommon)
        {   
            bool bresult = false;
            if (result == null)
            {
                return false;
            }

            //去掉对20 的忽略 大厦名部分可能没有问号
            if (entryCommon == "30" )
            {
                return false;
            }

            bresult = result.SelectMany(o => o).Any( CheckSimilarity );
                        
            if (bresult)
            {
                System.Console.WriteLine("VerfityA0003");
            }

            return bresult;
        }

        private bool CheckSimilarity(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return false;
            }

            string mansion = new SplitEntryResult(ChildImageObject.CategorySetting.DataFormat, result).GetMansion();

            return Logic.JaCitys.GetInstance().Mansions.AsParallel().OrderBy(t=>t.ID) 
                .Any(t => Check(mansion, t ));
        }

        private bool Check(string entryMansion, JaMansionItem jaMansionItem)
        {
            var dbMansion = jaMansionItem.Name;
            decimal checkSimilarity = jaMansionItem.MaxSimilarity;

            if (string.IsNullOrEmpty(entryMansion) || string.IsNullOrEmpty(dbMansion))
            {
                return false;
            }
            

            decimal maxSimilarity =-1;
            var compareString = new CompareString();
            for (int i = 0; i + dbMansion.Length <= entryMansion.Length; i++)
            {
                string mansion = entryMansion.Substring(i, Math.Min(entryMansion.Length - i, dbMansion.Length)); 
                decimal similarity = compareString.LevenshteinDistancePercent(mansion, dbMansion);
                maxSimilarity = similarity > maxSimilarity ? similarity : maxSimilarity;
                 
                
            }

            var resultsimilarity = ( maxSimilarity >= checkSimilarity ) && !maxSimilarity.Equals(100);
 
            return resultsimilarity;
             
        }
    }
}